<template>
</template>

<script>
import { file } from '@/cordova/';
import { mapGetters } from 'vuex';

export default {
  name: 'file',
  data() {
    return {};
  },
  created() {
    this.init();
  },
  computed: {
    ...mapGetters(['website']),
  },
  methods: {
    init() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否下载最新版本',
        })
        .then(() => {
          this.upload();
        })
        .catch(() => {
          // on cancel
        });
    },
    upload() {
      file().then((res) => {
        this.fileObj = res;
        this.fileObj.mkdir(this.website.appDir).then(() => {
          this.fileObj.download(
            this.website.appDir + this.updateInfo.filename,
            this.updateInfo.url,
            this.onprogress,
            this.success,
            this.err,
            null,
          );
        });
      });
    },
    onprogress(e) {
      if (e.lengthComputable) {
        this.speed = (`${e.loaded / e.total}`).substring(0, 4);
        const toast = this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: `正在更新${parseInt(this.speed * 100)}%`,
        });
      }
    },
    success(entry) {
      this.$toast.clear();
      this.fileObj.run(entry.toURL(), app);
    },
    err(err) {
      this.$toast.clear();
      this.$dialog.alert({
        message: '下载失败！',
      });
    },
  },
};
</script>

<style>
</style>
